/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * http://dangerousprototypes.com/docs/Bitbang#00001111_-_Reset_Bus_Pirate
 */
package buspirategui;

import java.io.UnsupportedEncodingException;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;

/**
 *
 * @author PiotrGl
 */
public class BusPirateDevice {

    public static final int NOMODE = 0;
    public static final int BBIO1 = 1;
    public static final int SPI1 = 2;
    public static final int I2C1 = 3;
    public static final int ART1 = 4;
    public static final int OW01 = 5;
    public static final int RAW1 = 6;
    private static SerialPort serialPort;
    private static int mode = NOMODE;

    public BusPirateDevice() {
    }

    public int Connect(String PortName) {
        serialPort = new SerialPort(PortName);
        try {
            serialPort.openPort();//Open serial port
            serialPort.setParams(SerialPort.BAUDRATE_115200,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE,
                    false,
                    false);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

            serialPort.addEventListener(new SerialPortReader());
            for (int i = 0; i < 20; i++) {
                serialPort.writeInt(0x00);
            }
            //serialPort.writeInt('i');
            //@SuppressWarnings("MismatchedReadAndWriteOfArray")
            //byte buffer[] = serialPort.readBytes(10);                  
            //System.out.println(buffer);
            //serialPort.writeBytes("This is a test string".getBytes());//Write data to port
            //this.serialPort = serialPort;
            //serialPort.closePort();//Close serial port
        } catch (SerialPortException ex) {
            System.out.println(ex);
            serialPort = null;
            return -1;
        }

        return 0;
    }

    public int Disconnect() {
        try {
            serialPort.closePort();
            serialPort = null;
            mode = 0;
        } catch (SerialPortException ex) {
            System.out.println(ex);
            return -1;
        }

        return 0;
    }

    public SerialPort getPort() {
        return serialPort;
    }
    
    public String getMode() {
        switch (mode) {
            case NOMODE:    return "NOMODE";
            case BBIO1:     return "BBIO1";
            case SPI1:      return "SPI";
            case I2C1:      return "I2C";
            case ART1:      return "ART1";
            case OW01:      return "1Wire";
            case RAW1:      return "Raw";
            default:        return "";
        }  
    }
    
    public void setMode(int aMode){
        if (serialPort != null){
        try { 
            mode = 0;
            switch (aMode) {
            case BBIO1:
                serialPort.writeInt(0x00);
                break;
            case SPI1:
                serialPort.writeInt(0x00);
                serialPort.writeInt(0x01);
                break;
            case I2C1:
                serialPort.writeInt(0x00);
                serialPort.writeInt(0x02);
                break;
            case ART1:
                serialPort.writeInt(0x00);
                serialPort.writeInt(0x03);
                break;
            case OW01:
                serialPort.writeInt(0x00);
                serialPort.writeInt(0x04);
                break;
            case RAW1:
                serialPort.writeInt(0x00);
                serialPort.writeInt(0x05);
                break;
            default:
                break;
        }  
            
            
            
        } catch (SerialPortException ex) {
            System.out.println(ex);
        }
        }       
    }

    public void send() {
        try {
            serialPort.writeInt('i');
            serialPort.writeInt('\n');
        } catch (SerialPortException ex) {
            System.out.println(ex);
        }
    }

    static class SerialPortReader implements SerialPortEventListener {

        @Override
        public void serialEvent(SerialPortEvent event) {
            if (event.isRXCHAR()) {//If data is available
                // if(event.getEventValue() == 1){//Check bytes count in the input buffer
                //Read data, if 10 bytes available 
                try {
                    if (event.isRXCHAR()) {
                        @SuppressWarnings("MismatchedReadAndWriteOfArray")
                        byte buffer[] = serialPort.readBytes();
                        String value = new String(buffer, "UTF-8");
                        System.out.println(value);
                        if ((mode == NOMODE)||(mode==BBIO1)) {
                            //set mode
                            //if (value.length() >= 5) 
                            {
                                if (value.indexOf("1") > 0) {
                                    if (value.length()>4)
                                        value = value.substring(value.lastIndexOf("1")-4, value.lastIndexOf("1")+1);
                                    if (value.substring(0, 1).equals("1")) 
                                        value=value.substring(1);
                                    if ("BBIO1".equals(value)) {
                                        mode = BBIO1;
                                        
                                    } else if ("SPI1".equals(value)) {
                                        mode = SPI1;
                                    } else if ("I2C1".equals(value)) {
                                        mode = I2C1;
                                    } else if ("ART1".equals(value)) {
                                        mode = ART1;
                                    } else if ("1W01".equals(value)) {
                                        mode = OW01;
                                    } else if ("BBIO1".equals(value)) {
                                        mode = RAW1;
                                    }
                                }
                            }                    
                        } else if (mode==SPI1){
                            
                        } else if (mode==I2C1){
                            
                        } else if (mode==ART1){
                            
                        } else if (mode==OW01){
                            
                        } else if (mode==RAW1){
                            
                        }


                    }
                } catch (SerialPortException ex) {
                    System.out.println(ex);
                } catch (UnsupportedEncodingException ex) {
                    System.out.println(ex);
                }
                //  }
            } else if (event.isCTS()) {//If CTS line has changed state
                if (event.getEventValue() == 1) {//If line is ON
                    System.out.println("CTS - ON");
                } else {
                    System.out.println("CTS - OFF");
                }
            } else if (event.isDSR()) {///If DSR line has changed state
                if (event.getEventValue() == 1) {//If line is ON
                    System.out.println("DSR - ON");
                } else {
                    System.out.println("DSR - OFF");
                }
            }
        }
    }
}
